package com.zhida.gooutcrawler.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zhida.gooutcrawler.R;
import com.zhida.gooutcrawler.activity.CrawlerActivity;
import com.zhida.gooutcrawler.activity.MainActivity;
import com.zhida.gooutcrawler.adapter.HomePagerAdapter;
import com.zhida.gooutcrawler.entity.Column;
import com.zhida.gooutcrawler.mvpview.IHomeView;
import com.zhida.gooutcrawler.presenter.HomePresenter;
import com.zhida.gooutcrawler.util.ColorUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;

/**
 * Created by ange on 2017/3/27.
 */

public class HomeFragment extends BaseMvpFragment<IHomeView, HomePresenter> implements IHomeView {

    @BindView(R.id.navigation_layout)
    LinearLayout mNavigationLayout;

    @BindView(R.id.tb_toolbar)
    Toolbar mToolbar;

    @BindView(R.id.column_name)
    TextView mColumnName;

    @BindView(R.id.total_text)
    TextView mTotalText;

    @BindView(R.id.tl_tabs)
    TabLayout mTabs;

    @BindView(R.id.vp_content)
    ViewPager mViewPager;

    private HomePagerAdapter contentAdapter;

    @NonNull
    @Override
    public HomePresenter createPresenter() {
        return new HomePresenter();
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initAllMembersView(View view, @Nullable Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        initContent();//初始化内容页
        initTab();//初始化选项卡
        initToolBar();//初始化toolbar
    }

    private void initContent() {
        //设置页面缓存数量
        mViewPager.setOffscreenPageLimit(3);

        //设置当前fragment
        mViewPager.setCurrentItem(1);

        //adapter
        contentAdapter = new HomePagerAdapter(getChildFragmentManager());
        mViewPager.setAdapter(contentAdapter);

        contentAdapter.addFragment(new HomePagerAdapter.Listener() {
            @Override
            public Fragment onLazyCreate() {
                return ColumnsFragment.newInstance();
            }
        }, "栏目");

        /*contentAdapter.addFragment(new HomePagerAdapter.Listener() {
            @Override
            public Fragment onLazyCreate() {
                return ColumnFragment.newInstance();
            }
        }, "采集测试");*/
    }

    private void initTab() {
        mTabs.setTabMode(TabLayout.MODE_FIXED);
        mTabs.setTabTextColors(ContextCompat.getColor(getActivity(), R.color.colorAccent), ContextCompat.getColor(getActivity(), R.color.white));//颜色
        mTabs.setSelectedTabIndicatorColor(ContextCompat.getColor(getActivity(), R.color.white));
        ViewCompat.setElevation(mTabs, 10);
        mTabs.setupWithViewPager(mViewPager);
    }

    public void initToolBar() {
        //toolbar
        if (mToolbar != null) {
            mToolbar.setTitle("");
            MainActivity activity = ((MainActivity) getActivity());
            activity.setSupportActionBar(mToolbar);
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.main, menu);

        //菜单图标着色
        MenuItem menuItem = menu.findItem(R.id.menu_add);
        if (menuItem != null) {
            ColorUtil.tintMenuIcon(getActivity(), menuItem, android.R.color.holo_red_light);
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_add:
                startActivity(new Intent(getActivity(), CrawlerActivity.class));
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /*eventbus */

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onColumnClick(ColumnsFragment.OnColumnCilckEvent event) {
        final Column column = event.getColumn();
        String title = column.getText();
        int position = contentAdapter.getPositionByTitle(title);
        if (position == -1) {
            //检查没有重复的title就创建一个新的
            contentAdapter.addFragment(new HomePagerAdapter.Listener() {
                @Override
                public Fragment onLazyCreate() {
                    return ColumnFragment.newInstance(column);
                }
            }, column.getText());
            contentAdapter.notifyDataSetChanged();
            position = contentAdapter.getCount() - 1;
        }

        //滑动到指定页
        mViewPager.setCurrentItem(position);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onColumnRefresh(ColumnFragment.OnColumnRefreshEvent event) {
        long total = event.getTotal();
        String columnName = event.getColumnName();
        mColumnName.setText("当前栏目: " + columnName);
        mTotalText.setText("采集总数: " + total);

        //废弃，设置tab的标题
        /*int pos = contentAdapter.getPositionByTitle(columnName);
        if (pos != -1) {
            HomePagerAdapter.Item item = contentAdapter.getItems().get(pos);
            item.setTitle(item.getTitle() + "(" + total + ")");
        }*/
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }
    /**
     * DrawerLayout侧滑菜单开关
     */
    /*@OnClick({R.id.toolbar_user_avatar, R.id.tv_username})
    public void toggleDrawer() {
        if (LoginContext.isLogin()) {
            //已登录
            ((MainActivity) getActivity()).toggleDrawer();
        } else {
            //未登录
            LoginActivity.launch(getActivity());
        }
    }*/


    /* 以下实现IHomeView的接口 */

}
